package fr.upstlse.glre.client.administration.profil.action;

import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.google.gwt.user.client.rpc.AsyncCallback;

import fr.upstlse.glre.client.administration.profil.AdminProfil;
import fr.upstlse.glre.client.utilitaires.ControlerUtil;
import fr.upstlse.glre.client.vo.user.UserVOGWT;
import fr.upstlse.glre.client.widgets.fields.UserFields;

public class AdminProfilEditionSubmit extends SelectionListener<ComponentEvent> {

	UserVOGWT user;
	UserFields userFields;
	AdminProfil adminProfil;

	public AdminProfilEditionSubmit(UserFields pUserFields,
			AdminProfil pAdminProfil) {
		super();

		this.userFields = pUserFields;
		this.adminProfil = pAdminProfil;
		this.user = adminProfil.getUser();
	}

	public void componentSelected(ComponentEvent ce) {
		user.setLogin((String) userFields.getLogin().getValue());
		user
				.setPassword((String) userFields.getMotDePasse().getValue());

		final MessageBox lInfoMessageBox = MessageBox.alert("Information", "Mise à jour en cours...", null);
		AsyncCallback<Object> lCallback = new AsyncCallback<Object>() {

			public void onFailure(Throwable pCaught) {
				lInfoMessageBox.hide();
				MessageBox.alert("Erreur", "Erreur mise à jour" + pCaught.getMessage(), null);
			}

			public void onSuccess(Object pResult) {
				lInfoMessageBox.hide();
				Info.display("Information", "Mis à jour avec succès", "");
				adminProfil.readingMode();
				adminProfil.getProfilPanel().add(
						adminProfil.getProfilReadingPanel());
				adminProfil.getProfilPanel().layout();
				adminProfil.getProfilPanel().remove(
						adminProfil.getProfilEditingPanel());
				adminProfil.getProfilPanel().layout();
				adminProfil.setEditionMode(false);

			}
		};

		ControlerUtil.getUserControlerServiceAsyncInstance()
				.updateUser(user, lCallback);
	}

}
